package com.opages.platform.common.config;

import com.opages.platform.common.config.basic.Configuration;
import com.opages.platform.extension.ExtensionLoader;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final class ConfigurationFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationFactory.class);

    private static final String SYSTEM_PROPERTY_NAME = "opages.config.name";
    private static final String ENV_PROPERTY_NAME = "OPAGES_CONFIG_NAME";

    public static final String FILE_ROOT_CONFIG = "config";
    public static final String FILE_ROOT_TYPE = "type";

    private static final String DEF_PROPERTY_NAME = "application.yml";

    private static Configuration FILE_INSTANCE;
    private static volatile Configuration instance = null;

    static {
        load();
    }

    private static void load() {
        String configName = System.getProperty(SYSTEM_PROPERTY_NAME);
        if(configName == null) {
            configName = System.getenv(ENV_PROPERTY_NAME);
        }
        if(configName == null) {
            configName = DEF_PROPERTY_NAME;
        }
        FILE_INSTANCE = new FileConfiguration(configName);
    }
    public static Configuration getInstance() {
        if (instance == null) {
            synchronized (Configuration.class) {
                if (instance == null) {
                    instance = buildConfiguration();
                }
            }
        }
        return instance;
    }

    public static Configuration getFileInstance() {
        return FILE_INSTANCE;
    }

    private static Configuration buildConfiguration() {
        String configTypeName = FILE_INSTANCE.getConfig(FILE_ROOT_CONFIG + "." + FILE_ROOT_TYPE);
        if(StringUtils.isNotEmpty(configTypeName)) {
            ConfigType configType = ConfigType.getType(configTypeName);
            if (ConfigType.file == configType) {
                return FILE_INSTANCE;
            }
            return ExtensionLoader.getExtension(Configuration.class,configType.name());
        }
        return ExtensionLoader.getExtension(Configuration.class);
    }

}
